package Servlets;

import Estructuras.Principales.PartnersPrincipal;
import Herramientas.Herramientas;
import TarryDAOS.PartnerDAO;
import TarryDTOS.PartnerDTO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Alan Gonzalez
 */
@WebServlet(name = "Proveedores", urlPatterns = {"/Proveedores"})
public class Proveedores extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
        } finally {
            String action = request.getParameter("action");
            HttpSession session = request.getSession();
            if (action.equals("principal")) {
                this.principal(request, response, session);
            } else if (action.equals("nuevoProveedor")) {
                this.nuevoProveedor(request, response, session);

            } else if (action.equals("nuevoProveedorRequest")) {
                this.nuevoProveedorRequest(request, response, session);
            } else if (action.equals("editarProveedor")) {
                this.principal(request, response, session);
            } else if (action.equals("editarProveedorRequest")) {
                this.principal(request, response, session);
            } else if (action.equals("eliminarProveedor")) {
                this.principal(request, response, session);

            } else {
                System.out.println("ERROR AL ENTRAR A UN SERVICIO DE | PROVEEDORES | EL SERVICIO : " + action + "  NO EXISTE");
            }
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * ALAN GONZALEZ CATALOGO PRINCIPAL DEPROVEEDORES
     *
     * @param request
     * @param response
     * @param session
     */
    public void principal(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Vector vPartners = new Vector();
        PartnerDAO partnerDAO = new PartnerDAO();
        PartnersPrincipal principal = new PartnersPrincipal();
        vPartners = partnerDAO.Partners();
        principal.setPartners(vPartners);
        session.setAttribute("principalPartners", principal);

        RequestDispatcher d = request.getRequestDispatcher("TarryJSP/PartnerJSP/adminPartners.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO MUETSRA LA INTERFAZ DE UN NUEVO PROVEEDOR
     *
     * @param request
     * @param response
     * @param session
     */
    public void nuevoProveedor(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        RequestDispatcher d = request.getRequestDispatcher("TarryJSP/PartnerJSP/nuevoPartner.jsp");
        try {
            d.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ALAN GONZALEZ SERVICIO QUE RECUPERA LOS DATOS DE LA INTERFAZ ANTERIOR
     *
     * @param request
     * @param response
     * @param session
     */
    public void nuevoProveedorRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        PartnerDTO partner = new PartnerDTO();
        partner.setTipoPartner(2); // TIPO PROVEEDOR COMO CONSTANTE 

        Vector errores = new Vector();
        // razon social
        if (request.getParameter("rs").length() > 0) {
            partner.setRazonSocial(request.getParameter("rs"));
        } else {
            errores.add("Ingrese La Razon Social");
        }

// nombres contacto
        if (request.getParameter("nc").length() > 0) {
            partner.setNombres(request.getParameter("nc"));
        } else {
            //partner.setNombres(request.getParameter("ND"));
            errores.add("Ingrese un Nombre De Contacto");
        }

// appelidos contacto
        if (request.getParameter("ac").length() > 0) {
            partner.setApellidos(request.getParameter("ac"));
        } else {
            //partner.setApellidos(request.getParameter("ND"));
            errores.add("Ingrese Un Apellido de Contacto");
        }

// direccion empresa
        if (request.getParameter("dir").length() > 0) {
            partner.setDireccion(request.getParameter("dir"));
        } else {
            errores.add("el campo de direccion es obligatorio");
        }

// telefono 1 
        String telefonos = new String();
        if (request.getParameter("tel1").length() > 0) {
            telefonos = request.getParameter("tel1");
            partner.setTelefonos(telefonos);
        } else {
            errores.add("El campo de telefono 1 es obligatorio");
        }

        if (request.getParameter("tel2").length() > 0) {
            telefonos += "  " + request.getParameter("tel2");
            partner.setTelefonos(telefonos);
        } else {
            partner.setTelefonos(telefonos + "");
        }

// email
        if (request.getParameter("mail").length() > 0) {
            Herramientas herramientas = new Herramientas();
            String email = request.getParameter("mail");
            boolean bandera = new Boolean(null);
            bandera = herramientas.validarEmail(email);

            if (bandera == true) {
                partner.setEmail(email);
            } else {
                errores.add("Introdusca un email Valido");
            }
        } else {
            errores.add("El campo Email del Proveedor es obligatorio");
        }

        if (errores.size() > 0) {
            PartnersPrincipal principal = new PartnersPrincipal();
            principal.setErrores(errores);
            principal.setnErrores(errores.size());
            session.setAttribute("principalPartners", principal);
            RequestDispatcher d = request.getRequestDispatcher("TarryJSP/PartnerJSP/nuevoPartner.jsp");
            try {
                d.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            PartnerDAO partnerDAO = new PartnerDAO();
            partnerDAO.nuevoProvedor(partner);
            RequestDispatcher d = request.getRequestDispatcher("TarryJSP/PartnerJSP/nuevoPartner.jsp");
            try {
                d.forward(request, response);
            } catch (ServletException ex) {
                Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Proveedores.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
